package com.web.surf.sample.eshop.faces.backing.beans;

import javax.faces.component.UICommand;
import javax.faces.event.ActionEvent;
import com.web.surf.sample.eshop.faces.interfaces.ISorter;

/**
 * Pager sorter - sorts ascending or descending goods page by chosen parameter
 * 
 * @author SavenkoNV
 */
public class PagerSorter implements ISorter {

	private DataPager pager;
	private boolean sortAscending = true;

	public String getDirection() {
		// TODO move to constants
		return sortAscending ? "ascending" : "descending";
	}

	public void sort(ActionEvent ae) {
		String sortLink = ((UICommand) ae.getComponent()).getId().toString();
		// If the same field is sorted, then reverse order, else sort the new
		// field ascending.
		if (pager.getSortField().equals(sortLink)) {
			sortAscending = !pager.isSortAscending();
			pager.executeSorting(sortLink, sortAscending);
		} else {
			sortAscending = true;
			pager.executeSorting(sortLink, sortAscending);
		}
	}

	// Spring setter
	public void setPager(DataPager pager) {
		this.pager = pager;
	}
}